﻿using AutoMapper;
using B.S.Material.Domain.BOM;
using B.S.Material.ErrorCode;
using B.S.Material.Wirth.Api.Applications.Command.MaterialsPickingDetailCommand;
using MediatR;
using SqlSugar;

namespace B.S.Material.Wirth.Api.Applications.Handler.MaterialsPickingDetailHandler
{
    public class CreaPLMaterialsPickingDetailHandler : IRequestHandler<CreaPLMaterialsPickingDetailCommand, ApiResult<object>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public CreaPLMaterialsPickingDetailHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<object>> Handle(CreaPLMaterialsPickingDetailCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            result.Code = ApiEnum.添加成功;
            result.MAG = ApiEnum.添加成功.ToString();
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    throw new Exception("表单明细至少有一条数据");
                }

                var list = await db.Queryable<MaterialsPickingDetail>().Where(x => x.IsDel != true && x.DetailID == request.Ids[0].PickingId).ToListAsync();
                list.ForEach(x =>
                {
                    x.IsDel = true;
                });
                db.Insertable(request.Ids);
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.添加失败;
                result.MAG = ApiEnum.添加失败.ToString() + "." + ex.Message;
                throw;
            }
            return result;
        }
    }
}
